//
//  MessageBuilder.swift
//  Chatup
//
//  Created by iron man on 2024/1/22.
//

import FirebaseAnalytics
import Foundation
import SwiftyJSON

typealias onMessage = (String?) -> Void
typealias onUploadRusult = (String?,Int?,String?) -> Void
///
/// 信息生成器
///
protocol MessageBuilder {
    associatedtype AbstractType
    func buildMessage(resouse: AbstractType, message: @escaping onMessage)
}

///
/// 资源文件类信息生成器
///
protocol MediaMessageBuilder: MessageBuilder {
    func uploadFile(filePath: URL, message: @escaping onUploadRusult)
}

///
/// 文本信息
///
class TextMessageBuilder: MessageBuilder {
    typealias AbstractType = String

    func buildMessage(resouse: String, message: @escaping onMessage) {
        message(resouse)
    }
}

class FileMessageBuilder: MediaMessageBuilder {
    typealias AbstractType = URL

    func buildMessage(resouse: URL, message: @escaping onMessage) {
        buildMessage(resouse: resouse, question: "", message: message)
    }

    func buildMessage(resouse: URL, question: String, message: @escaping onMessage) {
        uploadFile(filePath: resouse) { data, code, msg in
            
           
            if code == -1{
                DispatchQueue.main.async {
//                    NotificationCenter.default.post(name: Notification.Name("kGpt3OverSizeMessage"), object: nil)
                    message("-1")
                }
                return
            }
            
            if code == -2{
                DispatchQueue.main.async {
//                    NotificationCenter.default.post(name: Notification.Name("kGpt4OverSizeMessage"), object: nil)
                    message("-2")
                }
                return
            }
            
            guard let fileid = data else {
                message(nil)
                return
            }
            
            let ep_user_id: String = UserDefaults.standard.string(forKey: "ep_user_id") ?? "1"
            let url = "https://backend.aichattings.com/api/v2/chatgpt/askQuestionForFile?fileid=\(resouse)&question=\(question)&ep_user_id=\(ep_user_id)"
            var components = URLComponents(string: "https://backend.aichattings.com/api/v2/chatgpt/askQuestionForFile")

            // 添加查询参数
            let queryItems = [
                URLQueryItem(name: "fileid", value: fileid),
                URLQueryItem(name: "question", value: question),
                URLQueryItem(name: "ep_user_id", value: ep_user_id)
            ]
            components?.queryItems = queryItems
            if let url = components?.url {
                RequestManager.shared.getWithUrl(url) { json, _ in
                    if let data = json, let dic = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        if dic["code"] as! Int == -1 {
                            message("-1")
                        } else {
                            message(dic["data"] as? String)
                            Analytics.logEvent("feature_document_summarize", parameters: nil)
                        }

                    } else {
                        message(nil)
                    }
                } fail: { _, _, _ in
                    message(nil)
                }
            } else {
                print("无法构造URL")
                message(nil)
            }
        }
    }

    internal func uploadFile(filePath: URL, message: @escaping onUploadRusult) {
        RequestManager.shared.postWith("https://backend.aichattings.com/api/v2/chatgpt/uploadfile", fileURL: filePath, endpointUserId: UserDefaults.standard.string(forKey: "ep_user_id") ?? "1") { result in
            switch result {
                case .success(let data):
                    let json = JSON(data)
                    let code = json["code"].int
                    if let fileid = json["data"]["fileid"].string {
                        Analytics.logEvent("feature_document_uploaded", parameters: ["format": ""])
                        message(fileid,nil,nil)
                    } else {
                        code == -1 || code == -2 ? message(nil,code,String(code!)) : message(nil,0,json["msg"].string)
                    }

                case .failure:
                    // 处理错误
                    message(nil,0,nil)
            }
        }
    }
}

class DrawImageMessageBuilder: MessageBuilder {
    typealias AbstractType = String

    func buildMessage(resouse: String, message: @escaping onMessage) {
        
        let uid = UserDefaults.standard.string(forKey: "ep_user_id") ?? "1"
        
        RequestManager.shared.postWithJson("https://backend.aichattings.com/api/v2/chatgpt/texttoimage", parameters: ["topic": resouse, "ep_user_id": uid]) { result in

            switch result {
                case .success(let data):
                    let j = JSON(data)
                    if let url = j["data"]["url"].string {
                        Analytics.logEvent("feature_magination_draw", parameters: nil)
                        message(url)
                    } else {
                        message(String(j["code"].int64Value))
                    }
                case .failure(let e):
                    // 处理错误
                message(nil)
            }
        }
    }
}

class GetEmojiMessageBuilder: MessageBuilder {
    typealias AbstractType = String
    func buildMessage(resouse: String, message: @escaping onMessage) {
        Analytics.logEvent("feature_get_emoji", parameters: nil)
        message("Please help me convert the following content into the closest corresponding emoji :" + resouse)
    }
}

class TranslateMessageBuilder: MessageBuilder {
    typealias AbstractType = String
    func buildMessage(resouse: String, message: @escaping onMessage) {
        Analytics.logEvent("feature_translate", parameters: nil)
        let list = resouse.components(separatedBy: "#")
        let content: String = list.first ?? ""
        let language: String = list.last ?? ""
        message("Please translate the following content to  '\(content)' langugage：and answer me in the same language：'\(language)')")
    }
}

class RecognizeImageMessageBuilder: MediaMessageBuilder {
    func buildMessage(resouse: String, message: @escaping onMessage) {
        buildMessage(resouse: resouse, question: "", message: message)
    }

    func buildMessage(resouse: String, question: String, message: @escaping onMessage) {
        RequestManager.shared.postWithJson("https://backend.aichattings.com/api/v2/chatgpt/analysisimage", parameters: ["image_url": resouse,
                                                                                                                       "text": question,
                                                                                                                       "ep_user_id": UserDefaults.standard.string(forKey: "ep_user_id") ?? "1"]) { result in
            switch result {
                case .success(let data):
                    let json = JSON(data)
                    if let msg = json["data"].string, let code = json["code"].int {
                        if code == -1 {
                            message("-1")
                        } else {
                            message(msg)
                            Analytics.logEvent("feature_images_recognize", parameters: nil)
                        }
                    } else {
                        message(nil)
                    }

                case .failure:
                    message(nil)
            }
        }
    }

    func uploadFile(filePath: URL, message: @escaping onUploadRusult) {
        RequestManager.shared.postWith("https://backend.aichattings.com/api/v2/chatgpt/uploadfile", fileURL: filePath, endpointUserId: UserDefaults.standard.string(forKey: "ep_user_id") ?? "1") { result in
            switch result {
                case .success(let data):
                    let json = JSON(data)
                    let code = json["code"].int
                    if let fullurl = json["data"]["fullurl"].string {
                        if code == -1 {
                            message(nil,-1,"-1")
                        } else {
                            Analytics.logEvent("feature_recognize_images_uploaded", parameters: nil)
                            message(fullurl,200,nil)
                        }

                    } else {
                        code == -1 || code == -2 ? message(nil,code,String(code!)) : message(nil,0,json["msg"].string)
                    }

                case .failure:
                    // 处理错误
                    message(nil,0,nil)
            }
        }
    }

    typealias AbstractType = String
}

class LinkMessageBuilder: MessageBuilder {
    typealias AbstractType = String
    func buildMessage(resouse: String, message: @escaping onMessage) {
        Analytics.logEvent("feature_link_analyze", parameters: nil)
        message(resouse)
    }
}
